#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author： 胡浩浩
# datetime： 2021/12/28 16:21 
# ide： PyCharm
from Models.apiModel import api_model
from typing import List
from sqlalchemy.orm import Session
from Tools.database import engine
from Dependencies.db_depedencies import get_db
from Controllers.apiController import api_controller
from Schemas.apiSchema import api_schema
from fastapi import APIRouter, Depends, HTTPException

api_model.Base.metadata.create_all(bind=engine)
router = APIRouter()


@router.get("/api/get/list", response_model=List[api_schema.Api])
async def read_api_list(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    api_list = api_controller.get_api_list(db, skip=skip, limit=limit)
    return api_list


@router.get("/api/get/{api_id}", response_model=api_schema.Api)
async def read_api_by_id(api_id: int, db: Session = Depends(get_db)):
    db_api = api_controller.get_api_by_id(db, api_id=api_id)
    if db_api is None:
        raise HTTPException(status_code=404, detail="api not fund")
    return db_api


@router.post("/api/create", response_model=api_schema.Api)
async def create_api(api: api_schema.ApiCreate, db: Session = Depends(get_db)):
    db_api = api_controller.get_api_by_path(db, path=api.path)
    if db_api:
        raise HTTPException(status_code=400, detail="api already exit")
    return api_controller.create_api(db=db, api=api)
